﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace TTServer
{
    class SocketServer
    {
        public static int port = 44472;

        private Socket m_listenSocket = null;

        private Thread mainThread = null;

        private SocketServerThread st = null;

        private List<SocketServerThread> m_socketServerThreads = new List<SocketServerThread>();

        public void Start()
        {
            Terminate();

            mainThread = new Thread(new ThreadStart(MainLoop));
            mainThread.Name = "ServerSocket";
            mainThread.IsBackground = true;
            mainThread.Priority = ThreadPriority.Normal;
            mainThread.Start();
        }

        public void MainLoop()
        {
            try
            {
                m_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                m_listenSocket.Listen((int)SocketOptionName.MaxConnections);
                
                while (m_listenSocket != null)
                {
                    Socket s = m_listenSocket.Accept();

                    st = new SocketServerThread(s);
                    st.CreateAndStartThread();

                    m_socketServerThreads.Add(st);
                }
            }
            catch
            {
               
            }
            finally
            {
                
            }
        }

        public void Terminate()
        {

            if (st != null)
            {
                st.Terminate();
                st = null;
            }

            if (m_listenSocket != null)
            {
                try
                {
                    m_listenSocket.Close();
                    m_listenSocket = null;
                }
                catch
                {

                }
            }

            if (mainThread != null)
            {
                mainThread.Abort();
            }
        }
    }
}
